﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXF.Common;

namespace XXF.Assemblys
{
    /// <summary>
    /// 自动生成Model类
    /// 主要用于dynamic类型，可以在运行时自动生成model代码文件
    /// </summary>
    public class AutoModelList
    {
        private static string template = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace 【namespace】
{
    //配置表
    public class 【classname】
    {
        //XXF GetPagerResult AutoModelList自动生成类 车毅
        //此类目前仅做说明文档的使用，不编译入项目，删除则重新生成
        【content】
    }
}
";
        /// <summary>
        /// 自动生成代码方法
        /// </summary>
        /// <param name="path"></param>
        /// <param name="model"></param>
        /// <param name="namespacestr"></param>
        /// <param name="classname"></param>
        public void AutoCode(string path,object model,string namespacestr,string classname)
        {
            //string typename = namespacestr.Trim('.') + "." + classname;
            string content = "";
            if (model is Newtonsoft.Json.Linq.JContainer)
            {
                var ls = (model as Newtonsoft.Json.Linq.JContainer).ToList();
                for (int i = 0; i < ls.Count; i++)
                {
                    var item = ls[i] as Newtonsoft.Json.Linq.JProperty;
                    content += "public " + item.Value.Type.ToString() + " " + item.Name + " {get;set;}\r\n";
                }
            }
            else
            {
                foreach (var p in model.GetType().GetProperties())
                {
                    //content += string.Format("public {0} {1} {get;set;}", p.GetType().Name, p.Name);
                    content += "public " + p.GetType().Name + " " + p.Name + " {get;set;}";
                }
            }
           string cls =  AutoModelList.template.Replace("【namespace】", namespacestr).Replace("【classname】", classname).Replace("【content】", content);
           if (!System.IO.File.Exists(path))
           {
               IOHelper.CreateDirectory(path);
               System.IO.File.WriteAllText(path,cls);
           }
        }
    }
}
